<template>
	<div class="books">
    <book-info :bookInfo="bookInfo"></book-info>

    <comment-list :comments="comments"></comment-list>

    <template v-if="showAdd">
      <textarea
        v-model='queryData.comment'
        class='textarea'
        :maxlength='100'
        placeholder='请输入图书短评'
      ></textarea>

      <div class='location'>
        地理位置：
        <switch color='#EA5A49' :checked='queryData.location' @change='getGeo'></switch>
        <span class='text-primary'>{{ queryData.location }}</span>
      </div>

      <div class='phone'>
        手机型号：
        <switch color='#EA5A49' :checked='queryData.phone' @change='getPhone'></switch>
        <span class='text-primary'>{{ queryData.phone }}</span>
      </div>

      <button class="btn" @click='addComment'>
        评论
      </button>
    </template>
    <div v-else class='text-footer'>
      未登录或者已经评论过啦
    </div>
    <!-- 分享按钮 -->
    <button open-type='share' class="btn">转发给好友</button>
	</div>
</template>
<script>
import { get, post } from '@/utils/api'
import { showModal } from '@/utils/utils'
import bookInfo from './components/bookInfo'
import commentList from '@/components/commentList'

export default {
  name: 'bookDetail',
  data () {
    return {
      isbn: '',
      comments: [],
      bookInfo: {},
      userInfo: {},
      queryData: {
        comment: '',
        location: '',
        phone: ''
      }
    }
  },
  computed: {
    showAdd () {
      if (!this.userInfo.openId) return false
      if (this.comments.filter(item => item.open_id === this.userInfo.openId).length) return false
      return true
    }
  },
  components: {
    bookInfo,
    commentList
  },
  async mounted () {
    // 实现当前页面的转发
    wx.showShareMenu()
    this.isbn = this.$root.$mp.query.isbn
    await this.getDetail()
    this.userInfo = wx.getStorageSync('userInfo') || {}

    // 获取评论列表
    await this.getComments()
  },
  methods: {
    getPhone ({target: { value }}) {
      if (value) {
        const { model } = wx.getSystemInfoSync()
        this.queryData.phone = model
      } else {
        this.queryData.phone = ''
      }
    },
    getGeo ({target: { value }}) {
      // const ak = '6MKzyOTUYwnnuwouRX6V8CZOabgP7AaG'
      const ak = 'Gqk1kDkYcIDyjOFH96LoKCDa036erRFo'
      let url = 'http://api.map.baidu.com/reverse_geocoding/v3/'
      if (value) {
        wx.getLocation({
          success: ({latitude, longitude}) => {
            wx.request({
              url,
              data: {
                ak,
                location: `${latitude},${longitude}`,
                output: 'json',
                coordtype: 'wgs84ll'
              },
              success: res => {
                if (res.data.status === 0) {
                  this.queryData.location = res.data.result.addressComponent.city
                } else {
                  this.queryData.location = '未知地点'
                }
              }
            })
          }
        })
      } else {
        this.queryData.location = ''
      }
    },
    async getComments () {
      let comments = await get('/weapp/commentlist', { bookIsbn: this.bookInfo.isbn })
      this.comments = comments.data.commentList || []
      if (this.comments.length) {
        this.comments.map(item => {
          item.createTime = this.formatTime(item.create_time, 'Y-M-D h:m:s')
          delete item.create_time
        })
      }
    },
    // 格式化日期，如月、日、时、分、秒保证为2位数
    formatNumber (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    },
    // 参数number为毫秒时间戳，format为需要转换成的日期格式
    formatTime (number, format) {
      let time = new Date(number)
      let newArr = []
      let formatArr = ['Y', 'M', 'D', 'h', 'm', 's']
      newArr.push(time.getFullYear())
      newArr.push(this.formatNumber(time.getMonth() + 1))
      newArr.push(this.formatNumber(time.getDate()))

      newArr.push(this.formatNumber(time.getHours()))
      newArr.push(this.formatNumber(time.getMinutes()))
      newArr.push(this.formatNumber(time.getSeconds()))

      for (let i in newArr) {
        format = format.replace(formatArr[i], newArr[i])
      }
      return format
    },
    async addComment () {
      if (!this.queryData.comment) return false
      let queryData = {
        ...this.queryData,
        openId: this.userInfo.openId,
        bookIsbn: this.bookInfo.isbn
      }
      try {
        let res = await post('/weapp/addcommit', queryData)
        if (res.code === 0) {
          this.queryData.comment = ''
          this.getComments()
        } else {
          showModal('失败', res.data.msg)
        }
      } catch (e) {
        showModal('失败', e)
      }
    },
    async getDetail () {
      let bookInfo = await get('/weapp/bookDetail', { isbn: this.isbn })
      if (bookInfo.code === 0) {
        this.bookInfo = bookInfo.data
      }
      wx.setNavigationBarTitle({
        title: this.bookInfo.title
      })
    }
  },
  onShareAppMessage () {
    return {
      // title: 'test Title',
      // desc: 'desc!',
      // path: 'pages/bookDetail/main'
    }
  }
}
</script>
<style lang="scss" scoped>
  .books{
    // margin-top:10px;
    width: 100%;
    .textarea{
      width: 100%;
      height: 200rpx;
      background:#eee;
      padding: 10rpx;
      box-sizing: border-box;
    }

    .location{
      margin-top:10px;
      padding:5px 10px;
    }
    .phone{
      margin-top:10px;
      padding:5px 10px;
      
    }
  }
</style>